package com.dongchedi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dongchedi.entity.CustomerAddr;
import com.dongchedi.entity.CustomerLogin;
import com.dongchedi.mapper.CustomerAddrMapper;
import com.dongchedi.service.CustomerAddressService;
import com.dongchedi.utils.CheckUtil;
import com.dongchedi.utils.HostHolder;
import com.dongchedi.utils.constant.RedisConstantKey;
import com.dongchedi.utils.page.PageRequest;
import com.dongchedi.utils.page.PageResult;
import com.dongchedi.utils.page.PageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author leibidong
 * @description 用户地址实现类
 * @date 2021/6/25
 */
@Service
public class CustomerAddressServiceImpl implements CustomerAddressService {
    @Autowired
    CustomerAddrMapper customerAddrMapper;
    @Resource
    RedisTemplate<String,String> redisTemplate;
    @Resource
    HostHolder hostHolder;
    /*
     * @Author: leibidong
     * @Description:根据用户id查询所有地址信息
     * @Date: 2021/6/23 10:51
     * @Param: [customerId, pageNum, pageSize]
     * @Return: com.alibaba.fastjson.JSONArray
     **/
    @Override
    public JSONArray queryAllAddress(Integer customerId,Integer pageNum,Integer pageSize) {
        CustomerLogin customerLogin=hostHolder.getUser();
        if(customerId.equals(customerLogin.getId())) {
            String key = RedisConstantKey.getAllAddress(customerId);
            if (redisTemplate.opsForValue().get(key) != null) {
                return JSON.parseArray(redisTemplate.opsForValue().get(key));
            } else {
                PageHelper.startPage(pageNum, pageSize);
                PageRequest pageRequest = new PageRequest(pageNum, pageSize);
                List<CustomerAddr> list = customerAddrMapper.queryAllById(customerId);
                PageResult pageResult = PageUtil.getPageResult(pageRequest, new PageInfo<CustomerAddr>(list));
                JSONArray jsonArray = new JSONArray();
                int n = pageResult.getContent().size();
                if (n == 0) {
                    return jsonArray;
                }
                for (int i = 0; i < n; i++) {
                    JSONObject jsonObject = new JSONObject();
                    CustomerAddr c = (CustomerAddr) pageResult.getContent().get(i);
                    jsonObject.put("id", c.getId());
                    jsonObject.put("address", c.getAddress());
                    jsonObject.put("customerName", c.getCustomerName());
                    jsonObject.put("customerPhone", c.getCustomerPhone());
                    jsonObject.put("isDefault", c.getIsDefault());
                    jsonArray.add(jsonObject);
                }
                redisTemplate.opsForValue().set(key, jsonArray.toJSONString(), 3600, TimeUnit.SECONDS);
                return jsonArray;
            }
        }else {
            return new JSONArray();
        }

    }
    /*
     * @Author: leibidong
     * @Description:用户添加地址信息，1、如果第一次填写地址信息，将其设置为默认地址；2、如果地址信息已经存在，直接返回，无需插入数据库
     * 3、否则就插入数据库
     * @Date: 2021/6/23 11:23
     * @Param: [customerAddr]
     * @Return: java.lang.Integer
     **/
    @Override
    public Integer addCustomerAddress(CustomerAddr customerAddr) {
        CustomerLogin customerLogin=hostHolder.getUser();
        if(customerAddr.getCustomerId().equals(customerLogin.getId())&&CheckUtil.checkPhone(customerAddr.getCustomerPhone())) {
            List<CustomerAddr> list = customerAddrMapper.queryAllById(customerAddr.getCustomerId());
            if (list.size() == 0) {
                customerAddr.setIsDefault(1);
                Date date = new Date();
                Timestamp nousedate = new Timestamp(date.getTime());
                customerAddr.setCreateTime(nousedate);
                Integer integer = customerAddrMapper.addDefaultCustomerAddress(customerAddr);
                if (integer == null) {
                    return 0;
                } else {
                    String key = RedisConstantKey.getAllAddress(customerAddr.getCustomerId());
                    redisTemplate.delete(key);
                    return 2;
                }
            } else {
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getAddress().equals(customerAddr.getAddress()) && list.get(i).getCustomerName().equals(customerAddr.getCustomerName()) && list.get(i).getCustomerPhone().equals(customerAddr.getCustomerPhone())) {
                        return 1;
                    }
                }
                Date date = new Date();
                Timestamp nousedate = new Timestamp(date.getTime());
                customerAddr.setCreateTime(nousedate);
                Integer integer = customerAddrMapper.addCustomerAddress(customerAddr);
                if (integer == null) {
                    return 0;
                } else {
                    String key = RedisConstantKey.getAllAddress(customerAddr.getCustomerId());
                    redisTemplate.delete(key);
                    return 2;
                }
            }
        }else {
            return 0;
        }
    }
    /*
     * @Author: leibidong
     * @Description:更改地址信息:1、根据用户id和地址id查询当前修改内容是否存在，如果不存在，则修改失败；
     * 2、如果存在则修改后返回。
     * @Date: 2021/6/26 10:55
     * @Param: [customerAddr]
     * @Return: com.alibaba.fastjson.JSONObject
     **/
    @Override
    public JSONObject updateCustomerAddress(CustomerAddr customerAddr) {
        CustomerLogin customerLogin=hostHolder.getUser();
        if(customerAddr.getCustomerId().equals(customerLogin.getId())&& CheckUtil.checkPhone(customerAddr.getCustomerPhone())) {
            Integer integer = customerAddrMapper.queryByAddressId(customerAddr.getCustomerId(), customerAddr.getId());
            JSONObject jsonObject = new JSONObject();
            if (integer != null) {
                Integer integer1 = customerAddrMapper.updateCustomerAddress(customerAddr);
                CustomerAddr customerAddr1 = customerAddrMapper.queryAddressIdAndCustomerId(customerAddr.getCustomerId(), customerAddr.getId());
                jsonObject.put("id", customerAddr1.getId());
                jsonObject.put("address", customerAddr1.getAddress());
                jsonObject.put("customerName", customerAddr1.getCustomerName());
                jsonObject.put("customerPhone", customerAddr1.getCustomerPhone());
                jsonObject.put("isDefault", customerAddr1.getIsDefault());
                String key = RedisConstantKey.getAllAddress(customerAddr.getCustomerId());
                redisTemplate.delete(key);
                return jsonObject;
            } else {
                return jsonObject;
            }
        }else {
            return new JSONObject();
        }
    }
    /*
     * @Author: leibidong
     * @Description:删除用户地址:根据用户地址id和用户id进行删除。
     * @Date: 2021/6/26 11:30
     * @Param: [id, customerId]
     * @Return: com.alibaba.fastjson.JSONObject
     **/
    @Override
    public JSONObject deleteCustomerAddress(Integer id, Integer customerId) {
        CustomerLogin customerLogin=hostHolder.getUser();
        if(customerId.equals(customerLogin.getId())) {
        Integer integer=customerAddrMapper.deletebyId(id,customerId);
        System.out.println(integer);
        JSONObject jsonObject=new JSONObject();
        if(integer!=0){
            String key = RedisConstantKey.getAllAddress(customerId);
            redisTemplate.delete(key);
            jsonObject.put("status","ok");
            return jsonObject;
        }
        return jsonObject;
        }else {
            return new JSONObject();
        }

    }
    /*
     * @Author: leibidong
     * @Description:更该用户默认地址：先查询用户的默认地址，1、如果默认地址的id和参数customerAddressId，则直接返回成功
     * 2、如果不一样，将参数customerAddressId对应记录设置为默认地址，再将原来的字段取消默认地址
     * @Date: 2021/6/26 12:02
     * @Param: [customerId, customerAddressId]
     * @Return: com.alibaba.fastjson.JSONObject
     **/
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public JSONObject updateCustomerDefaultAddress(Integer customerId, Integer customerAddressId) {
        JSONObject jsonObject=new JSONObject();
        CustomerLogin customerLogin=hostHolder.getUser();
        if(customerId.equals(customerLogin.getId())) {
        CustomerAddr customerAddr=customerAddrMapper.queryCustomerAddressId(customerId);
        if(customerAddr!=null){
            if(customerAddr.getId().equals(customerAddressId)){
                jsonObject.put("status","ok");
            }else {
                Integer i1=customerAddrMapper.updateCustomerDefaultAddress(customerId,customerAddressId);
                if(i1!=0){
                Integer i=customerAddrMapper.updateCustomerDefaultAddressZero(customerId,customerAddr.getId());
                if(i!=0) {
                    String key = RedisConstantKey.getAllAddress(customerId);
                    redisTemplate.delete(key);
                    jsonObject.put("status", "ok");
                }
                }
            }
        }
        return jsonObject;
    }else {
            return jsonObject;
        }
    }

}
